<template>
  <div class="tool-page">
    <div class="tool-header">
      <h1>Excel数据分配器</h1>
      <p>上传Excel文件，选择数据字段并分配到容器</p>
    </div>
    
    <div class="excel-viewer">
      <!-- 文件上传区域 -->
      <div class="upload-section">
        <div class="upload-area" @click="triggerFileInput" @dragover.prevent @drop="handleDrop">
          <div class="upload-content">
            <i class="fa fa-file-excel-o upload-icon"></i>
            <h3>点击或拖拽Excel文件到这里</h3>
            <p>支持 .xlsx, .xls 格式</p>
            <input
              ref="fileInput"
              type="file"
              accept=".xlsx,.xls"
              @change="handleFileSelect"
              style="display: none"
            />
          </div>
        </div>
        
        <div v-if="fileName" class="file-info">
          <p><strong>已选择文件:</strong> {{ fileName }}</p>
          <p><strong>文件大小:</strong> {{ fileSize }}</p>
          <button @click="clearFile" class="clear-btn">清除文件</button>
        </div>
      </div>

      <!-- 左右布局：左边设置，右边容器 -->
      <div v-if="tableData.length > 0" class="distribution-layout">
        <!-- 左边：分配设置 -->
        <div class="settings-side">
          <div class="settings-panel">
            <h3>分配设置</h3>
            
            <!-- 字段选择 -->
            <div class="setting-group">
              <label class="setting-label">选择合计字段：</label>
              <select v-model="selectedField" class="setting-select">
                <option value="">请选择字段</option>
                <option v-for="(header, index) in tableData[0]" :key="index" :value="index">
                  {{ header || `列${index + 1}` }}
                </option>
              </select>
            </div>
            
            <!-- 容器数量设置 -->
            <div class="setting-group">
              <label class="setting-label">容器数量：</label>
              <input 
                v-model.number="containerCount" 
                type="number" 
                min="1" 
                max="10" 
                class="setting-input"
                @change="updateDistribution"
              >
            </div>
            
            <!-- 分配按钮 -->
            <div class="setting-group">
              <button @click="calculateDistribution" class="distribute-btn" :disabled="!selectedField">
                计算分配
              </button>
            </div>
            
            <!-- 分配结果摘要 -->
            <div v-if="distributionResult" class="result-summary">
              <h4>分配摘要</h4>
              <p>总数据量：<strong>{{ totalValue }}</strong></p>
              <p>容器数量：<strong>{{ containerCount }}</strong></p>
              <p>平均分配：<strong>{{ (totalValue / containerCount).toFixed(2) }}</strong></p>
            </div>
            
             <!-- 优化分配按钮 -->
            <div v-if="distributionResult" class="setting-group">
              <button @click="optimizeDistribution" class="optimize-btn">
                <i class="fa fa-refresh"></i> 优化分配
              </button>
            </div>

            <!-- 下载按钮 -->
            <div v-if="distributionResult" class="setting-group">
              <button @click="downloadExcel" class="download-btn">
                <i class="fa fa-download"></i> 下载分配结果
              </button>
            </div>
            
          </div>
        </div>

        <!-- 右边：容器显示 -->
        <div class="containers-side">
          <div v-if="distributionResult" class="containers-section">
            <h3>分配结果</h3>
            <div class="containers-grid">
              <div v-for="(container, index) in distributionResult" :key="index" class="container-item">
                <div class="container-header">
                  <span>容器 {{ index + 1 }}</span>
                  <span class="container-value">合计：{{ container.total }}</span>
                </div>
                <div class="container-data" 
                     @dragover.prevent 
                     @drop="handleDrop($event, index)"
                     :class="{ 'drag-over': dragOverContainer === index }">
                  <div v-for="(item, itemIndex) in container.items" :key="itemIndex" 
                       class="data-row" 
                       draggable="true"
                       @dragstart="handleDragStart($event, index, itemIndex)"
                       @dragend="handleDragEnd">
                    <span class="first-column">{{ item.firstColumn }}</span>
                    <span class="selected-column">{{ item.selectedColumn }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <div v-else class="no-distribution">
            <i class="fa fa-cubes"></i>
            <p>请先设置分配参数并计算分配</p>
          </div>
        </div>
      </div>

      <!-- 表格数据展示区域 -->
      <div v-if="tableData.length > 0" class="sheet-section">
        <div class="table-info">
          <p>数据行数: {{ tableData.length - 1 }} 行，列数: {{ tableData[0] ? tableData[0].length : 0 }} 列</p>
        </div>
        <div class="table-container">
          <div class="table-scroll">
            <table class="data-table">
              <thead>
                <tr>
                  <th v-for="(header, index) in tableData[0]" :key="index" 
                      :class="{ 'selected-field': selectedField === index }">
                    {{ header || `列${index + 1}` }}
                  </th>
                  <th v-if="distributionResult" class="container-column">分配容器</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(row, rowIndex) in tableData.slice(1)" :key="rowIndex">
                  <td v-for="(cell, cellIndex) in row" :key="cellIndex" 
                      :class="{ 'selected-field': selectedField === cellIndex }">
                    {{ cell }}
                  </td>
                  <td v-if="distributionResult" class="container-column">
                    {{ getRowContainer(rowIndex) }}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
      
      <div v-else-if="!loading && fileName" class="no-data">
        <p>Sheet1中没有数据</p>
      </div>

      <!-- 错误提示 -->
      <div v-if="error" class="error-message">
        <i class="fa fa-exclamation-triangle"></i>
        {{ error }}
      </div>
    </div>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'

export default {
  name: 'ExcelViewer',
  data() {
    return {
      fileName: '',
      fileSize: '',
      fileData: null,
      sheetNames: [],
      selectedSheet: '',
      tableData: [],
      loading: false,
      error: '',
      selectedField: '',
      containerCount: 3,
      distributionResult: null,
      totalValue: 0,
      dragOverContainer: -1,
      dragData: null
    }
  },
  methods: {
    triggerFileInput() {
      this.$refs.fileInput.click()
    },
    
    handleFileSelect(event) {
      const file = event.target.files[0]
      if (file) {
        this.processFile(file)
      }
    },
    
    handleDrop(event) {
      event.preventDefault()
      const file = event.dataTransfer.files[0]
      if (file) {
        this.processFile(file)
      }
    },
    
    async processFile(file) {
      // 验证文件类型
      const validTypes = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 
                         'application/vnd.ms-excel']
      if (!validTypes.includes(file.type) && !file.name.match(/\.(xlsx|xls)$/)) {
        this.error = '请选择有效的Excel文件 (.xlsx 或 .xls)'
        return
      }
      
      // 验证文件大小 (限制为10MB)
      if (file.size > 10 * 1024 * 1024) {
        this.error = '文件大小不能超过10MB'
        return
      }
      
      this.loading = true
      this.error = ''
      this.fileName = file.name
      this.fileSize = this.formatFileSize(file.size)
      
      try {
        const arrayBuffer = await this.readFileAsArrayBuffer(file)
        const workbook = XLSX.read(arrayBuffer, { type: 'array' })
        
        this.fileData = workbook
        this.sheetNames = workbook.SheetNames
        
        if (this.sheetNames.length > 0) {
          // 只读取第一个工作表（Sheet1）的数据
          this.loadSheet1Data()
        }
      } catch (err) {
        this.error = '文件读取失败: ' + err.message
        this.clearFile()
      } finally {
        this.loading = false
      }
    },
    
    readFileAsArrayBuffer(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = (e) => resolve(e.target.result)
        reader.onerror = (e) => reject(e)
        reader.readAsArrayBuffer(file)
      })
    },
    
    loadSheet1Data() {
      if (!this.fileData || this.sheetNames.length === 0) return
      
      try {
        // 只读取第一个工作表（Sheet1）
        const firstSheetName = this.sheetNames[0]
        const worksheet = this.fileData.Sheets[firstSheetName]
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
        
        // 确保数据格式正确
        this.tableData = jsonData.filter(row => row.length > 0)
      } catch (err) {
        this.error = 'Sheet1数据读取失败: ' + err.message
        this.tableData = []
      }
    },
    
    formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes'
      const k = 1024
      const sizes = ['Bytes', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },
    
    clearFile() {
      this.fileName = ''
      this.fileSize = ''
      this.fileData = null
      this.sheetNames = []
      this.selectedSheet = ''
      this.tableData = []
      this.error = ''
      this.selectedField = ''
      this.distributionResult = null
      this.totalValue = 0
      this.$refs.fileInput.value = ''
    },
    
    // 计算数据分配
    calculateDistribution() {
      if (!this.selectedField || this.tableData.length <= 1) {
        this.error = '请先选择合计字段'
        return
      }
      
      try {
        const fieldIndex = parseInt(this.selectedField)
        const dataRows = this.tableData.slice(1) // 排除表头
        
        // 创建包含第一列和所选列的数据对象
        const dataWithFirstColumn = dataRows.map(row => ({
          firstColumn: row[0] || '', // 第一列数据
          selectedColumn: row[fieldIndex] || '', // 所选列数据
          numericData: this.parseNumericValue(row[fieldIndex]) // 数值数据和小数位数
        }))
        
        // 提取数值数据用于分配计算
        const values = dataWithFirstColumn.map(item => item.numericData.value)
        
        // 计算总和
        const rawTotal = values.reduce((sum, val) => sum + val, 0)
        
        if (rawTotal === 0) {
          this.error = '所选字段没有有效的数值数据'
          return
        }
        
        // 检测最大小数位数
        const maxDecimalPlaces = Math.max(...dataWithFirstColumn.map(item => item.numericData.decimalPlaces))
        
        // 根据小数位数格式化总和
        this.totalValue = this.formatNumber(rawTotal, maxDecimalPlaces)
        
        // 平均分配到容器
        this.distributionResult = this.distributeData(dataWithFirstColumn, maxDecimalPlaces)
        
      } catch (err) {
        this.error = '数据分配计算失败: ' + err.message
      }
    },
    
    // 解析数值并检测小数位数
    parseNumericValue(value) {
      if (value === null || value === undefined || value === '') return { value: 0, decimalPlaces: 0 }
      
      const strValue = value.toString()
      // 尝试转换为数字
      const numValue = parseFloat(strValue.replace(/[^0-9.-]/g, ''))
      
      if (isNaN(numValue)) return { value: 0, decimalPlaces: 0 }
      
      // 检测小数位数
      const decimalMatch = strValue.match(/\.(\d+)/)
      const decimalPlaces = decimalMatch ? decimalMatch[1].length : 0
      
      return { value: numValue, decimalPlaces }
    },
    
    // 数据分配算法
    distributeData(dataWithFirstColumn, maxDecimalPlaces) {
      const containers = Array.from({ length: this.containerCount }, () => ({
        items: [],
        rawTotal: 0,
        total: 0
      }))
      
      // 按数值降序排序，优先分配大数值
      const sortedData = [...dataWithFirstColumn].sort((a, b) => b.numericData.value - a.numericData.value)
      
      for (const dataItem of sortedData) {
        // 找到当前总和最小的容器
        let minContainerIndex = 0
        let minTotal = containers[0].rawTotal
        
        for (let i = 1; i < containers.length; i++) {
          if (containers[i].rawTotal < minTotal) {
            minTotal = containers[i].rawTotal
            minContainerIndex = i
          }
        }
        
        // 将数据项添加到该容器
        containers[minContainerIndex].items.push({
          firstColumn: dataItem.firstColumn,
          selectedColumn: dataItem.selectedColumn
        })
        containers[minContainerIndex].rawTotal += dataItem.numericData.value
      }
      
      // 格式化每个容器的合计值
      containers.forEach(container => {
        container.total = this.formatNumber(container.rawTotal, maxDecimalPlaces)
      })
      
      return containers
    },
    
    // 数字格式化方法
    formatNumber(value, decimalPlaces) {
      if (decimalPlaces === 0) {
        return Math.round(value)
      }
      return parseFloat(value.toFixed(decimalPlaces))
    },
    
    // 更新分配
    updateDistribution() {
      if (this.distributionResult) {
        this.calculateDistribution()
      }
    },
    
    // 拖拽开始
    handleDragStart(event, containerIndex, itemIndex) {
      this.dragData = {
        containerIndex,
        itemIndex
      }
      event.dataTransfer.effectAllowed = 'move'
      event.dataTransfer.setData('text/plain', `${containerIndex},${itemIndex}`)
      
      // 添加拖拽样式
      event.target.style.opacity = '0.4'
    },
    
    // 拖拽结束
    handleDragEnd(event) {
      this.dragOverContainer = -1
      event.target.style.opacity = '1'
    },
    
    // 拖拽放置
    handleDrop(event, targetContainerIndex) {
      event.preventDefault()
      this.dragOverContainer = -1
      
      if (!this.dragData) return
      
      const { containerIndex: sourceContainerIndex, itemIndex } = this.dragData
      
      // 如果拖拽到同一个容器，不做任何操作
      if (sourceContainerIndex === targetContainerIndex) {
        this.dragData = null
        return
      }
      
      // 移动数据项
      this.moveItem(sourceContainerIndex, itemIndex, targetContainerIndex)
      this.dragData = null
    },
    
    // 移动数据项并重新计算合计
    moveItem(sourceContainerIndex, itemIndex, targetContainerIndex) {
      if (!this.distributionResult) return
      
      // 获取要移动的数据项
      const itemToMove = this.distributionResult[sourceContainerIndex].items[itemIndex]
      
      if (!itemToMove) return
      
      // 从源容器移除
      this.distributionResult[sourceContainerIndex].items.splice(itemIndex, 1)
      
      // 添加到目标容器
      this.distributionResult[targetContainerIndex].items.push(itemToMove)
      
      // 重新计算两个容器的合计值
      this.recalculateContainerTotal(sourceContainerIndex)
      this.recalculateContainerTotal(targetContainerIndex)
    },
    
    // 重新计算容器合计
    recalculateContainerTotal(containerIndex) {
      if (!this.distributionResult || !this.selectedField) return
      
      const container = this.distributionResult[containerIndex]
      const fieldIndex = parseInt(this.selectedField)
      
      // 重新计算原始合计值
      container.rawTotal = container.items.reduce((sum, item) => {
        const numericValue = this.parseNumericValue(item.selectedColumn)
        return sum + numericValue.value
      }, 0)
      
      // 检测小数位数
      const maxDecimalPlaces = Math.max(...container.items.map(item => {
        const numericValue = this.parseNumericValue(item.selectedColumn)
        return numericValue.decimalPlaces
      }))
      
      // 格式化合计值
      container.total = this.formatNumber(container.rawTotal, maxDecimalPlaces)
    },
    
    // 获取行对应的容器编号
    getRowContainer(rowIndex) {
      if (!this.distributionResult || !this.tableData.length) return ''
      
      // 获取第一列的值（用于匹配）
      const firstColumnValue = this.tableData[rowIndex + 1][0]
      
      // 在所有容器中查找包含该第一列值的容器
      for (let containerIndex = 0; containerIndex < this.distributionResult.length; containerIndex++) {
        const container = this.distributionResult[containerIndex]
        const foundItem = container.items.find(item => item.firstColumn === firstColumnValue)
        
        if (foundItem) {
          return `容器 ${containerIndex + 1}`
        }
      }
      
      return '未分配'
    },
    
    // 优化分配
    optimizeDistribution() {
      if (!this.distributionResult || this.distributionResult.length < 2) {
        this.error = '需要至少2个容器才能进行优化'
        return
      }
      
      const iterations = Math.floor(this.containerCount / 2)
      
      for (let i = 0; i < iterations; i++) {
        // 找到合计最大和最小的容器
        const { maxContainerIndex, minContainerIndex } = this.findMaxMinContainers()
        
        if (maxContainerIndex === minContainerIndex) {
          // 如果最大和最小是同一个容器，说明已经平衡
          break
        }
        
        // 在最大容器中找到最大的值
        const maxItemIndex = this.findMaxItemInContainer(maxContainerIndex)
        // 在最小容器中找到最小的值
        const minItemIndex = this.findMinItemInContainer(minContainerIndex)
        
        if (maxItemIndex === -1 || minItemIndex === -1) {
          break
        }
        
        // 交换两个值
        this.swapItems(maxContainerIndex, maxItemIndex, minContainerIndex, minItemIndex)
      }
      
      // 重新计算所有容器的合计值
      this.recalculateAllContainerTotals()
    },
    
    // 找到合计最大和最小的容器
    findMaxMinContainers() {
      let maxTotal = -Infinity
      let minTotal = Infinity
      let maxContainerIndex = -1
      let minContainerIndex = -1
      
      this.distributionResult.forEach((container, index) => {
        if (container.rawTotal > maxTotal) {
          maxTotal = container.rawTotal
          maxContainerIndex = index
        }
        if (container.rawTotal < minTotal) {
          minTotal = container.rawTotal
          minContainerIndex = index
        }
      })
      
      return { maxContainerIndex, minContainerIndex }
    },
    
    // 在容器中找到最大的值
    findMaxItemInContainer(containerIndex) {
      const container = this.distributionResult[containerIndex]
      if (!container || container.items.length === 0) return -1
      
      let maxValue = -Infinity
      let maxIndex = -1
      
      container.items.forEach((item, index) => {
        const numericValue = this.parseNumericValue(item.selectedColumn)
        if (numericValue.value > maxValue) {
          maxValue = numericValue.value
          maxIndex = index
        }
      })
      
      return maxIndex
    },
    
    // 在容器中找到最小的值
    findMinItemInContainer(containerIndex) {
      const container = this.distributionResult[containerIndex]
      if (!container || container.items.length === 0) return -1
      
      let minValue = Infinity
      let minIndex = -1
      
      container.items.forEach((item, index) => {
        const numericValue = this.parseNumericValue(item.selectedColumn)
        if (numericValue.value < minValue) {
          minValue = numericValue.value
          minIndex = index
        }
      })
      
      return minIndex
    },
    
    // 交换两个容器中的项目
    swapItems(container1Index, item1Index, container2Index, item2Index) {
      const container1 = this.distributionResult[container1Index]
      const container2 = this.distributionResult[container2Index]
      
      // 交换项目
      const temp = container1.items[item1Index]
      container1.items[item1Index] = container2.items[item2Index]
      container2.items[item2Index] = temp
    },
    
    // 重新计算所有容器的合计值
    recalculateAllContainerTotals() {
      this.distributionResult.forEach((container, index) => {
        this.recalculateContainerTotal(index)
      })
    },
    
    // 下载Excel文件
    downloadExcel() {
      if (!this.distributionResult || !this.tableData.length) {
        this.error = '没有可下载的数据'
        return
      }
      
      try {
        // 创建新的工作表数据，包含容器分配列
        const downloadData = []
        
        // 添加表头（包含容器分配列）
        const headers = [...this.tableData[0], '分配容器']
        downloadData.push(headers)
        
        // 添加数据行（包含容器分配信息）
        for (let i = 1; i < this.tableData.length; i++) {
          const row = [...this.tableData[i], this.getRowContainer(i - 1)]
          downloadData.push(row)
        }
        
        // 创建工作簿和工作表
        const wb = XLSX.utils.book_new()
        const ws = XLSX.utils.aoa_to_sheet(downloadData)
        
        // 设置列宽
        const colWidths = headers.map(() => ({ width: 15 }))
        ws['!cols'] = colWidths
        
        // 添加工作表到工作簿
        XLSX.utils.book_append_sheet(wb, ws, '分配结果')
        
        // 生成文件名：使用上传文件名 + "重新分配"后缀
        let filename = '分配结果.xlsx'
        if (this.fileName) {
          // 移除原文件扩展名，添加"重新分配"后缀
          const baseName = this.fileName.replace(/\.[^/.]+$/, '')
          filename = `${baseName}_重新分配.xlsx`
        }
        
        // 下载文件
        XLSX.writeFile(wb, filename)
        
      } catch (err) {
        this.error = '下载失败: ' + err.message
      }
    }
  }
}
</script>

<style scoped>
.excel-viewer {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.upload-section {
  margin-bottom: 2rem;
}

.upload-area {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 3rem 2rem;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fafafa;
}

.upload-area:hover {
  border-color: #3498db;
  background-color: #f0f9ff;
}

.upload-content .upload-icon {
  font-size: 3rem;
  color: #27ae60;
  margin-bottom: 1rem;
}

.upload-content h3 {
  margin-bottom: 0.5rem;
  color: #2c3e50;
}

.upload-content p {
  color: #666;
  margin: 0;
}

.file-info {
  margin-top: 1rem;
  padding: 1rem;
  background-color: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #27ae60;
}

.file-info p {
  margin: 0.5rem 0;
}

.clear-btn {
  background-color: #e74c3c;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 0.5rem;
}

.clear-btn:hover {
  background-color: #c0392b;
}

/* 左右布局样式 */
.distribution-layout {
  display: grid;
  grid-template-columns: 280px 1fr;
  gap: 1.5rem;
  margin: 1.5rem 0;
}

/* 左边设置区域 */
.settings-side {
  background: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  padding: 1rem;
}

.settings-panel h3 {
  margin: 0 0 1rem 0;
  color: #333;
  font-size: 1.1rem;
}

.setting-group {
  margin-bottom: 1rem;
}

.setting-label {
  display: block;
  font-weight: 600;
  color: #333;
  margin-bottom: 0.5rem;
  font-size: 0.9rem;
}

.setting-select,
.setting-input {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 0.9rem;
}

.distribute-btn {
  width: 100%;
  background: #007bff;
  color: white;
  border: none;
  padding: 0.75rem;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 600;
}

.distribute-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.download-btn {
  width: 100%;
  background: #28a745;
  color: white;
  border: none;
  padding: 0.75rem;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 600;
  margin-top: 1rem;
}

.download-btn:hover {
  background: #218838;
}

.download-btn .fa {
  margin-right: 0.5rem;
}

.optimize-btn {
  width: 100%;
  background: #ff9800;
  color: white;
  border: none;
  padding: 0.75rem;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 600;
  margin-top: 0.5rem;
}

.optimize-btn:hover {
  background: #f57c00;
}

.optimize-btn .fa {
  margin-right: 0.5rem;
}

/* 分配结果摘要 */
.result-summary {
  margin-top: 1rem;
  padding: 0.75rem;
  background: #f8f9fa;
  border-radius: 4px;
  font-size: 0.85rem;
}

.result-summary h4 {
  margin: 0 0 0.5rem 0;
  color: #333;
  font-size: 0.95rem;
}

.result-summary p {
  margin: 0.2rem 0;
  color: #666;
}

/* 右边容器区域 */
.containers-side {
  background: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  padding: 1rem;
}

.containers-section h3 {
  margin: 0 0 1rem 0;
  color: #333;
  font-size: 1.1rem;
}

.containers-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 1rem;
}

.container-item {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  background: white;
}

.container-header {
  background: #f8f9fa;
  padding: 0.75rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e0e0e0;
  font-weight: 600;
}

.container-value {
  color: #007bff;
  font-weight: bold;
}

.container-data {
  /* 移除固定高度和滚动条，让高度根据内容自适应 */
  min-height: 40px;
  transition: background-color 0.2s;
}

.container-data.drag-over {
  background-color: #e3f2fd;
  border: 2px dashed #2196f3;
}

.data-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  padding: 0.5rem 0.75rem;
  border-bottom: 1px solid #f0f0f0;
  font-size: 0.8rem;
  cursor: move;
  transition: background-color 0.2s;
}

.data-row:hover {
  background-color: #f5f5f5;
}

.data-row:last-child {
  border-bottom: none;
}

.data-header {
  display: grid;
  grid-template-columns: 1fr 1fr;
  padding: 0.5rem 0.75rem;
  background: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
  font-weight: 600;
  font-size: 0.8rem;
}

.data-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  padding: 0.5rem 0.75rem;
  border-bottom: 1px solid #f0f0f0;
  font-size: 0.8rem;
}

.data-row:last-child {
  border-bottom: none;
}

.first-column {
  color: #666;
}

.selected-column {
  color: #e74c3c;
  text-align: right;
}

/* 未分配状态 */
.no-distribution {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #999;
}

.no-distribution .fa {
  font-size: 2rem;
  margin-bottom: 0.5rem;
}

.no-distribution p {
  margin: 0;
  font-size: 0.9rem;
}

/* 表格区域样式 */
.sheet-section {
  margin-top: 2rem;
}

.table-container {
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
}

.table-info {
  padding: 1rem;
  background-color: #f8f9fa;
  border-bottom: 1px solid #ddd;
}

.table-info p {
  margin: 0;
  color: #666;
  font-size: 0.9rem;
}

.table-scroll {
  max-height: 600px;
  overflow: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 0.9rem;
}

.data-table th,
.data-table td {
  border: 1px solid #ddd;
  padding: 0.75rem;
  text-align: left;
  min-width: 100px;
}

.data-table th {
  background-color: #f2f2f2;
  font-weight: bold;
  position: sticky;
  top: 0;
  z-index: 1;
}

.data-table tbody tr:nth-child(even) {
  background-color: #f8f9fa;
}

.data-table tbody tr:hover {
  background-color: #e3f2fd;
}

.selected-field {
  background-color: #fff3cd !important;
  border-color: #ffeaa7 !important;
}

.container-column {
  background-color: #e8f5e8 !important;
  border-color: #c8e6c9 !important;
  font-weight: bold;
  text-align: center;
  min-width: 100px;
}

.loading {
  padding: 2rem;
  text-align: center;
  color: #666;
}

.loading .fa-spin {
  margin-right: 0.5rem;
}

.no-data {
  padding: 2rem;
  text-align: center;
  color: #666;
}

.error-message {
  padding: 1rem;
  background-color: #ffeaea;
  border: 1px solid #f5c6cb;
  border-radius: 6px;
  color: #721c24;
  margin-top: 1rem;
}

.error-message .fa {
  margin-right: 0.5rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .excel-viewer {
    padding: 1rem;
  }
  
  .upload-area {
    padding: 2rem 1rem;
  }
  
  .setting-group {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
  
  .setting-label {
    min-width: auto;
  }
  
  .containers-grid {
    grid-template-columns: 1fr;
  }
  
  .table-scroll {
    max-height: 400px;
  }
  
  .data-table th,
  .data-table td {
    padding: 0.5rem;
    font-size: 0.8rem;
  }
}
</style>